
<h2>Syntax</h2>

<pre class="brush:python">
import re

result = re.sub(pattern, repl, string, count=0, flags=0);
</pre>

<h2>Simple Examples</h2>

<pre class="brush:python">
result = re.sub('abc',  '',    input)           # Delete pattern abc
result = re.sub('abc',  'def', input)           # Replace pattern abc -> def
result = re.sub(r'\s+', ' ',   input)           # Eliminate duplicate whitespaces using wildcards
result = re.sub('abc(def)ghi', r'\1', input)    # Replace a string with a part of itself
</pre>

<b>Note:</b> Take care to always prefix patterns containing \ escapes with raw strings (by adding an r in front of the string). Otherwise the \ is used as an escape sequence and the regex won't work.

<h2>Advance Usage</h2>

<h3>Replacement Function</h3>

Instead of a replacement string you can provide a function performing dynamic replacements based on the match string like this:

<pre class="brush:python">
def my_replace(m):
    if <some condition>:
       return &lt;replacement variant 1>
    return &lt;replacement variant 2>

result = re.sub("\w+", my_replace, input)
</pre>

<h3>Count Replacements</h3>

When you want to know how many replacements did happen use re.subn() instead:

<pre class="brush:python">result = re.subn(pattern, replacement, input)
print ('Result: ', result[0])
print ('Replacements: ', result[1])
</pre>

<h3>Using Backreferences</h3>

<h4>Numeric Backreferences</h4>
To use back reference define capture groups using () and reference to those using \1, \2, and so on. <b>Do not forget the 'r' prefix on the
back reference string, otherwise \1 will be interpreted as a character.</b>

<pre>result = re.sub("(\d+) (\w+)", r"\2 \1")</pre>

<h4>Named Backreferences</h4>

For named backreferences define a named capture group (?<name>) and 
reference using \g<name>. Again ensure to add the 'r' prefix on the
backreference string.

<pre>result = re.sub("(?&lt;number>\d+) (?&lt;word>\w+)", r"\g&lt;word> \g&lt;number>")</pre>

<hr/>

<p>See also <?add example='Python re.match'?> <?add example='Regex Overview'?></p>
